package com.jason.redCherry.interecptor;

import com.jason.redCherry.common.Global;
import com.jason.redCherry.entity.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.StrutsStatics;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Jason on 2016/8/18.
 */
@Component
@Scope("prototype")
public class LoginCheckInterceptor extends MethodFilterInterceptor {

    private Log log = LogFactory.getLog(LoginCheckInterceptor.class);

    private ActionContext actionContext;

    @Override
    protected String doIntercept(ActionInvocation invocation) throws Exception {

        actionContext = invocation.getInvocationContext();

        String methodName = invocation.getProxy().getActionName();

        HttpServletRequest request = (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
        HttpServletResponse resp = (HttpServletResponse) actionContext.get(StrutsStatics.HTTP_RESPONSE);

        if (!checkLogin()) {
            return "login";
        }

        return invocation.invoke();
    }

    /**
     * 检查登陆
     *
     * @return
     */
    private boolean checkLogin() {

        User currentUser = (User) this.actionContext.getSession().get(Global.SESSION_CURRENT_USER);

        if (currentUser == null) {
            return false;
        }
        return true;

    }


}
